import config
import time
db = config.mysqldb


modelClassCache = {}

# 交易记录，每天一个表
class LocalLog():
    #指定数据库
    #__bind_key__ = 'trade'

    # 定义表名
    #__tablename__ = 'PriceDiffRatio_'
    # 定义列对象
    id = db.Column(db.Integer, primary_key=True)
    datets    = db.Column(db.Integer)

    Pid     = db.Column(db.Integer)
    logIndex     = db.Column(db.Integer)
    message = db.Column(db.Text(65536))  #探测利率
    logTime     = db.Column(db.String(64))

    def toJson(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    def save(self):
    	# 快捷保存数据库对象到数据库中
        db.session.add(self)
        db.session.commit()

    def onlySave(self):
    	# 快捷保存数据库对象到数据库中
        db.session.add(self)

    @classmethod
    def table_exists(cls):
        engine = db.get_engine()
        return cls.metadata.tables[cls.__tablename__].exists(engine)

def GetTradeLogClass(datets):
    global modelClassCache
    dayStr = time.strftime("%Y-%m-%d", time.localtime(datets))
    className = f"LocalLog_{dayStr}"
    classobj = None
    if className in modelClassCache:
        classobj = modelClassCache[className]
    else:
        tableName = className
        classobj = type(className,(LocalLog, db.Model),{'__tablename__': tableName})
        modelClassCache[className] = classobj
        db.create_all()

    return classobj

def GetTradeLogClassWithDay(dayString, appName):
    global modelClassCache
    #dayStr = time.strftime("%Y-%m-%d", time.localtime(datets))
    className = f"LocalLog_{appName}_{dayString}"
    classobj = None
    if className in modelClassCache:
        classobj = modelClassCache[className]
    else:
        tableName = className
        classobj = type(className,(LocalLog, db.Model),{'__tablename__': tableName})
        modelClassCache[className] = classobj
        db.create_all()

    return classobj
